// src/stores/auth.ts
import { defineStore } from 'pinia'

export const useAuthStore = defineStore('auth', {
  state: () => {
    // 从本地存储恢复状态
    return {
      user: JSON.parse(localStorage.getItem('user') || 'null'),
      token: localStorage.getItem('token') || null,
      isAuthenticated: localStorage.getItem('token') ? true : false,
      loading: false,
      error: null
    }
  },
  
  actions: {
    async login(username: string, password: string) {
      try {
        this.loading = true;
        this.error = null;
        
        const response = await fetch('http://localhost:8080/api/auth/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ username, password }),
        });

        if (!response.ok) {
          const errorText = await response.text();
          throw new Error(`登录失败: ${errorText}`);
        }

        const data = await response.json();
        
        // 创建和保存用户对象
        const user = {
          id: data.id,
          username: data.username,
          email: data.email
        };
        
        // 更新状态
        this.user = user;
        this.token = data.token;
        this.isAuthenticated = true;
        
        // 保存到本地存储
        localStorage.setItem('user', JSON.stringify(user));
        localStorage.setItem('token', data.token);
        
        return true;
      } catch (error) {
        this.error = error instanceof Error ? error.message : '登录失败';
        return false;
      } finally {
        this.loading = false;
      }
    },
    
    logout() {
      // 清除状态
      this.user = null;
      this.token = null;
      this.isAuthenticated = false;
      
      // 清除本地存储
      localStorage.removeItem('user');
      localStorage.removeItem('token');
    }
  }
});